import { isNavigationFailure } from 'vue-router';
import type { Router, RouteRecordName } from 'vue-router';
import { PageEnum } from '@/enums/pageEnum';
import { storage } from '@/utils';
import { ACCESS_TOKEN } from '@/stores/mutation-types';
import type { redirectLoginPageData } from './types';
import type { ICustomWindow } from '@/plugin/naive-ui';
import { NotFoundPageRoute } from '@/router/base';
import { useAsyncRouteStoreOut } from '@/stores/modules/asyncRoute';
import { useAppStoreOut } from '@/stores/modules/app';

const LOGIN_PATH = PageEnum.BASE_LOGIN;
const whitePathList = [LOGIN_PATH]; // no redirect whitelist

export function createRouterGuards(router: Router): void {
  router.beforeEach((to, from, next) => {
    const loadingBar = (window as unknown as ICustomWindow)['$loadingBar'] || null;
    loadingBar && loadingBar.start();
    if (from.path === LOGIN_PATH && to.name === PageEnum.ERROR_PAGE.replace('/', '')) {
      next(PageEnum.ERROR_PAGE);
      return;
    }

    // whiteList 可以直接进入
    if (whitePathList.includes(to.path as PageEnum)) {
      next();
      return;
    }

    const token = storage.get(ACCESS_TOKEN);
    console.log('token', token);

    if (!token) {
      if (to.meta.ignoreAuth) {
        next();
        return;
      }

      // redirect login page
      const redirectData: redirectLoginPageData = {
        path: LOGIN_PATH,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData);
      return;
    }

    // 添加404
    const isErrorPage = router.getRoutes().findIndex((item) => item.name === NotFoundPageRoute.name);
    if (isErrorPage === -1) {
      router.addRoute(NotFoundPageRoute);
    }

    next();
    loadingBar && loadingBar.finish();
  });

  router.afterEach((to, from, failure) => {
    const appStore = useAppStoreOut();
    const { currentMenuRoute } = appStore;
    // 任何类型的导航失败
    if (isNavigationFailure(failure)) {
      console.log('failure navigation', failure);
    }

    const token = storage.get(ACCESS_TOKEN);
    if (token && to.name === PageEnum.BASE_LOGIN_NAME) {
      router.replace({ name: PageEnum.BASE_MAIN_NAME });
    }

    // 设置keepAlive组件
    const asyncRouteStore = useAsyncRouteStoreOut();
    const keepAliveComponentList = asyncRouteStore.getKeepAliveComponentList;
    const currentToName = to.matched.find((item) => item.name === to.name)?.name;
    if (currentToName && !keepAliveComponentList.includes(currentToName) && to.meta?.isKeepAlive) {
      keepAliveComponentList.push(currentToName);
      asyncRouteStore.setKeepAliveComponentList(keepAliveComponentList);
    } else if (!to.meta?.isKeepAlive) {
      const index = keepAliveComponentList.findIndex((name) => name === currentToName);
      index !== -1 && keepAliveComponentList.splice(index, 1);
      asyncRouteStore.setKeepAliveComponentList(keepAliveComponentList);
    }

    // 设置初始化currentMenuRoute
    if (to.meta.isMenu) {
      appStore.$patch((state) => {
        state.currentMenuRoute = { meta: to.meta, path: to.path, name: to.name as RouteRecordName };
      });
    }

    const loadingBar = (window as unknown as ICustomWindow)['$loadingBar'] || null;
    loadingBar && loadingBar.finish();
  });

  router.onError((error) => {
    console.log(error, '路由错误');
  });
}
